from app.services.ItemService import ItemService
from sqlalchemy.orm import Session
from app.models.item import Item


class ItemServiceImpl(ItemService):
    def __init__(self):
        self.model = Item

    def create(self, db: Session, obj_in):
        # 将传入的对象转换为字典，并创建模型实例
        db_obj = self.model(**obj_in.dict())
        db.add(db_obj)
        db.commit()
        db.refresh(db_obj)
        return db_obj

    def get(self, db: Session, id: int):
        return db.query(self.model).filter(self.model.id == id).first()
        
    def get_all(self, db: Session):
        return db.query(self.model).all()

    def update(self, db: Session, db_obj, obj_in):
        obj_data = obj_in.dict(exclude_unset=True)
        for field, value in obj_data.items():
            setattr(db_obj, field, value)
        db.add(db_obj)
        db.commit()
        db.refresh(db_obj)
        return db_obj

    def delete(self, db: Session, db_obj):
        db.delete(db_obj)
        db.commit()
        return db_obj

    def get_by_title(self, db: Session, *, title: str):
        return db.query(Item).filter(Item.title == title).first()

item_crud = ItemServiceImpl()